package main

import (
	"encoding/json"
	"fmt"
	"gLogService/common"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"time"
)

type MsgData struct {
	Cmd   string
	Level string
	Desc  string
}

var (
	CurExeDir       = ""
	CurExeUpperDir  = ""
	ICOFile         = ""
	CurLogDir       = ""
	nlogNum         = 0
	FoodInfoPath    = ""
	FoodFeaturePath = ""
	FoodMenuDir     = ""
	TaskIdList      = ""
	UUID            uint64
	NutritionFile   = ""
	RobotDBPath     = ""
	RobotBillPath   = ""
	billAutoID      uint64
)

func main() {
	defer file.Close()
	// fmt.Printf("current thread id= %d\n", windows.GetCurrentThreadId())
	ICOFile = filepath.Join(CurExeDir, "favicon.png")
	CurExeUpperDir, _ = filepath.Split(CurExeDir)
	TaskIdList = filepath.Join(CurExeUpperDir, "syncHeartBeatList")
	FoodInfoPath = filepath.Join(CurExeUpperDir, "adytum", "foodInfo")
	NutritionFile = filepath.Join(FoodInfoPath, "菜名-热量-糖份-脂肪-蛋白质")
	FoodFeaturePath = filepath.Join(CurExeUpperDir, "adytum", "foodfeature")
	FoodMenuDir = filepath.Join(CurExeUpperDir, "adytum", "menu")
	fmt.Printf("CurExe=%s, \n CurExeUpperDir=%s \n FoodInfo=%s \n FoodFeature=%s \n",
		CurExeDir, CurExeUpperDir, FoodInfoPath, FoodFeaturePath)

	IsExist, _ := common.PathExists(TaskIdList)
	if !IsExist {
		os.MkdirAll(TaskIdList, os.ModePerm)
	}
	IsExist, _ = common.PathExists(FoodInfoPath)
	if !IsExist {
		os.MkdirAll(FoodInfoPath, os.ModePerm)
	}
	IsExist, _ = common.PathExists(FoodMenuDir)
	if !IsExist {
		os.MkdirAll(FoodMenuDir, os.ModePerm)
	}
	IsExist, _ = common.PathExists(NutritionFile)
	if !IsExist {
		f, _ := os.Create(NutritionFile)
		defer f.Close()
	}

	go func() {
		// 创建开机延迟同步文件
		// StartupDelaySync: { Cmd:"syncHeartBeat", "TaskId":"StartupDelaySync" }
		UUID++
		StartupDelaySyncFile := fmt.Sprintf("%s/%d_%d_127001.syn", TaskIdList, time.Now().Unix(), UUID)
		StartupDelaySync := make(map[string]interface{})
		StartupDelaySync["Cmd"] = "syncHeartBeat"
		StartupDelaySync["TaskId"] = "StartupDelaySync"
		fileStartupDelaySync, _ := os.OpenFile(StartupDelaySyncFile, os.O_WRONLY|os.O_CREATE, 0666)
		defer fileStartupDelaySync.Close()
		syncJsonData, _ := json.Marshal(StartupDelaySync)
		fileStartupDelaySync.Write(syncJsonData)

		muxFeaLibrary := http.NewServeMux()
		muxFeaLibrary.HandleFunc("/queryMenu", queryMenu)
		muxFeaLibrary.HandleFunc("/queryFoodInfo", queryFoodInfo)
		muxFeaLibrary.HandleFunc("/queryFoodImgUrl", queryFoodImgUrl)
		muxFeaLibrary.HandleFunc("/addFoodInfo", addFoodInfo)
		muxFeaLibrary.HandleFunc("/delFoodInfo", delFoodInfo)
		muxFeaLibrary.HandleFunc("/delFixFoodFea", delFixFoodFea)
		muxFeaLibrary.HandleFunc("/editFoodInfo", editFoodInfo)
		muxFeaLibrary.HandleFunc("/foodImage/", foodImageShow)
		muxFeaLibrary.HandleFunc("/syncHeartBeat", syncHeartBeat)
		muxFeaLibrary.HandleFunc("/queryFoodEnergy", queryFoodEnergy)
		muxFeaLibrary.HandleFunc("/editFoodEnergy", editFoodEnergy)
		muxFeaLibrary.HandleFunc("/queryAllMenus", queryAllMenus)
		muxFeaLibrary.HandleFunc("/queryMenuInfo", queryMenuInfo)
		muxFeaLibrary.HandleFunc("/setCurrentMenu", setCurrentMenu) //弃用，改由机器人本地存储当前使用的菜单名
		muxFeaLibrary.HandleFunc("/delMeun", delMeun)
		muxFeaLibrary.HandleFunc("/editMenuContent", editMenuContent)
		muxFeaLibrary.HandleFunc("/autoAddCurrentMenu", autoAddCurrentMenu) //目的：当一台机器人中新增菜后，需要加入到当前菜单中
		muxFeaLibrary.HandleFunc("/favicon.ico", FaviconICOHandle)
		http.ListenAndServe(":9001", muxFeaLibrary)
	}()

	go func() {
		RobotBillPath = filepath.Join(CurExeUpperDir, "adytum", "billingImage")
		IsExist, _ := common.PathExists(RobotBillPath)
		if !IsExist {
			os.MkdirAll(RobotBillPath, os.ModePerm)
		}
		RobotDBPath = filepath.Join(CurExeUpperDir, "adytum", "robotdb.db")

		initRobotdb()
		initRobotdbAdminUser()

		muxReport := http.NewServeMux()
		muxReport.HandleFunc("/favicon.ico", FaviconICOHandle)
		//用户操作
		muxReport.HandleFunc("/user_login", user_login)
		muxReport.HandleFunc("/user_queryname", user_queryname)
		muxReport.HandleFunc("/user_querydetail", user_querydetail)
		muxReport.HandleFunc("/user_delete", user_delete)
		muxReport.HandleFunc("/user_edit", user_edit)
		muxReport.HandleFunc("/user_add", user_add)
		//账单操作
		muxReport.HandleFunc("/bill_add", bill_add) //含挂账
		muxReport.HandleFunc("/bill_query", bill_query)
		muxReport.HandleFunc("/bill_countmoney", bill_countmoney)
		muxReport.HandleFunc("/bill_detail", bill_detail)
		muxReport.HandleFunc("/bill_imageShow/", bill_imageShow)
		muxReport.HandleFunc("/bill_chargeSearch", bill_chargeSearch)       //根据手机号模糊搜索未销账的挂账单
		muxReport.HandleFunc("/bill_crossoffAccount", bill_crossoffAccount) //根据账单号销账
		//用户登陆操作及报表
		muxReport.HandleFunc("/action_record", action_record)           //用户动作记录及返回需要数据
		muxReport.HandleFunc("/action_switch_user", action_switch_user) //切换用户时查询并返回需要数据
		muxReport.HandleFunc("/action_query", action_query)             //用户动作记录查询
		muxReport.HandleFunc("/action_record_query", action_record_query)
		muxReport.HandleFunc("/report_imageUpload", report_imageUpload)
		muxReport.HandleFunc("/report_imageShow/", report_imageShow)

		http.ListenAndServe(":10001", muxReport)
	}()

	muxLogger := http.NewServeMux()
	muxLogger.HandleFunc("/logger/writing", recvLoggerInfo)
	muxLogger.HandleFunc("/logger/test", loggertest)
	muxLogger.Handle("/", http.FileServer(http.Dir("./Log")))
	muxLogger.HandleFunc("/favicon.ico", FaviconICOHandle)
	if err := http.ListenAndServe(":9000", muxLogger); err != nil {
		fmt.Println("3")

		log.Fatal("ListenAndServe logger writing: ", err)
	}
}

func FaviconICOHandle(w http.ResponseWriter, r *http.Request) {
	content, _ := ioutil.ReadFile(ICOFile)
	w.Write(content)
}
